﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace LiteratureManage.Web.ViewModels
{
    using LiteratureManage.Domain;
    using LiteratureManage.Domain.Models;

    public class LiteratureSearchViewModel
    {
        public string ArticleName { get; set; }

        public string SubjectCatalog { get; set; }

        public string ArticleSource { get; set; }

        public string AuthorName { get; set; }

        public DateTime? BeginDate { get; set; }

        public DateTime? EndDate { get; set; }

        public LiteratureSearchableTerm CreateSearchableTerm()
        {
            var literature = new Literature()
            {
                ArticleName = this.ArticleName,
                SubjectCatalog = this.SubjectCatalog,
                ArticleSource = this.ArticleSource
            };
            Author author = null;
            author = AttachProperty<Author, string>(author, () => String.IsNullOrEmpty(this.AuthorName), a => a.Name = this.AuthorName);
            var dateInterval = new ArticlePublishDateInterval()
            {
                BeginDate = this.BeginDate,
                EndDate = this.EndDate
            };
            return new LiteratureSearchableTerm()
            {
                Literature = literature,
                Author = author,
                DateInterval = dateInterval
            };
        }

        private T AttachProperty<T, TValue>(T obj, Func<bool> condition, Action<T> action) where T : class, new()
        {
            if (!condition())
            {
                if (obj == null)
                    obj = new T();

                action(obj);
            }

            return obj;
        }
    }
}
